package com.example.aircraft.panel;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.aircraft.MyApplication;
import com.example.aircraft.R;
import com.example.aircraft.database.MySqlManager;
import com.example.aircraft.database.MySqliteHelper;
import com.example.aircraft.database.SQLiteInterface;
import com.example.aircraft.database.User_Data;

import java.io.IOException;


public class StorePanel extends Activity {

    private final String[] titles = {"炸弹道具", "弹药道具", "血量道具"};
    private final String[] prices = {"500", "400", "300"};
    private String[] number;
    //图片集合
    private final int[] icons = {R.drawable.prop_bomb, R.drawable.prop_bullet, R.drawable.prop_blood};

    private final int[] buttons ={R.drawable.shop};

    private int chooseTool;
    private  String name;
    private User_Data user_data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //如果是网络获取道具数量的话，这部分可能需要改动
        name= DualSignPanel.getUser_data().getUSER_NAME();
        user_data = DualSignPanel.getUser_data();

        number = new String[]{String.valueOf(user_data.getSHEILD()),
                String.valueOf(user_data.getCLUSTER()),
                String.valueOf(user_data.getHEMOPHAGIA())};

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_panel);

        TextView textView = findViewById(R.id.current_credit_store);
        textView.setText(String.valueOf(user_data.getCREDITS()));

        ListView listView = findViewById(R.id.lv);
        //创建一个Adapter的实例
        MyBaseAdapter mAdapter = new MyBaseAdapter();
        //加载适配器
        listView.setAdapter(mAdapter);

    }

    static class ViewHolder {
        TextView title;
        TextView price;
        ImageView iv;
        ImageButton imageButton;
        TextView number;////////////////
    }

    ////////
    public void updateView(){

        //如果是网络获取道具数量的话，这部分可能需要改动（每次购买后更新页面）

        user_data = DualSignPanel.getUser_data();
        assert user_data != null;
        number = new String[]{String.valueOf(user_data.getSHEILD()),
                String.valueOf(user_data.getCLUSTER()),
                String.valueOf(user_data.getHEMOPHAGIA())};

        TextView textView = findViewById(R.id.current_credit_store);
        textView.setText(String.valueOf(user_data.getCREDITS()));
        ListView listView = findViewById(R.id.lv);
        //创建一个Adapter的实例
        MyBaseAdapter mAdapter = new MyBaseAdapter();
        //加载适配器
        listView.setAdapter(mAdapter);

    }


    public void toBuy() {
        android.app.AlertDialog.Builder alertdialogbuilder = new android.app.AlertDialog.Builder(this);
        alertdialogbuilder.setMessage("确定要购买" + titles[chooseTool] +"吗");
        alertdialogbuilder.setPositiveButton("确定", click1);
        alertdialogbuilder.setNegativeButton("取消", click2);
        AlertDialog alertDialog = alertdialogbuilder.create();
        alertDialog.show();
    }

    private DialogInterface.OnClickListener click1 = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            confirmOrder();
            dialog.cancel();
            updateView();
        }
    };

    private DialogInterface.OnClickListener click2 = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    };


    private void confirmOrder(){
        new Thread() {
            @Override
            public void run() {
                Log.i("client", "send message to server");
                MyApplication.getWriter().println("333_514#"+chooseTool+",0");
                MyApplication.getWriter().flush();
                String content = "";
                while (true) {
                    try {
                        if ((content = MyApplication.getIn().readLine()) != null)
                            break;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                String[] command = content.split("#|,");
                if ("111".equals(command[0])) {
                    Log.d("REGTEST", "购买成功");
                    user_data.updateCREDITS(Integer.parseInt(prices[chooseTool]));
                    //购买到道具并且扣除积分
                    switch (chooseTool) {
                        case 1:
                            user_data.updateSHEILD(1);
                            break;
                        case 2:
                            user_data.updateCLUSTER(1);
                            break;
                        case 3:
                            user_data.updateHEMOPHAGIA(1);
                            break;
                        default:
                            break;
                    }
                    MySqlManager.updateDate2(user_data);
                }
            }
        }.start();

    }


    class MyBaseAdapter extends BaseAdapter {
        //需要适配的数据
        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public Object getItem(int i) {
            return titles[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(StorePanel.this, R.layout.item, null);
                holder = new ViewHolder();
                holder.title = convertView.findViewById(R.id.title);
                holder.price = convertView.findViewById(R.id.price);
                holder.iv = convertView.findViewById(R.id.iv);
                holder.imageButton = convertView.findViewById(R.id.buyit);
                holder.number = convertView.findViewById(R.id.number);//////////////
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.title.setText(titles[i]);
            holder.price.setText(prices[i]);
            holder.iv.setImageResource(icons[i]);
            holder.imageButton.setImageResource(buttons[0]);
            holder.number.setText(number[i]);////////////////////

            holder.imageButton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    chooseTool = i+1;
                    toBuy();
                }
            });

            return convertView;
        }

    }

}
